package com.job.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.job.mapper.MessageMapper;
import com.job.pojo.Message;
import com.job.pojo.dto.MessageDTO;
import com.job.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.rmi.RemoteException;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocket{
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    private String userId;

    //静态成员变量，全局
    private static MessageMapper messageMapper;
    @Autowired
    public void setRedisUtil(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }


    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        //加入map
        webSocketMap.put(userId, this);
        addOnlineCount();           //在线数加1
        log.info("用户{}连接成功,当前在线人数为{}", userId, getOnlineCount());
        try {
            sendMessage(String.valueOf(this.session.getQueryString()));
        } catch (IOException e) {
            log.error("IO异常");
        }
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        webSocketMap.remove(userId);
        subOnlineCount();           //在线数减1
        log.info("用户{}关闭连接！当前在线人数为{}", userId, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("来自客户端用户：{} 消息:{}",userId, message);
        MessageDTO messageDTO = null;
        Message mes = new Message();
        try {
             messageDTO = JSON.parseObject(message, MessageDTO.class);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new RemoteException("消息格式不正确");
        }

        BeanUtils.copyProperties(messageDTO,mes);
        mes.setFromId(Integer.valueOf(userId));
        String conversationId = MessageUtil.getConversationId(Integer.valueOf(userId), messageDTO.getToId());
        mes.setConversationId(conversationId);
        mes.setStatus(0);
        mes.setCreateTime(LocalDateTime.now());
        messageMapper.insert(mes);
        String string = JSONObject.toJSONString(mes);

        sendMessageByUserId(String.valueOf(messageDTO.getToId()),string);
    }

//    private void messageSave(Message mes, Integer toId){
//        threadPoolTaskExecutor.execute(()->{
//            mes.setFromId(Integer.valueOf(userId));
//            String conversationId = MessageUtil.getConversationId(Integer.valueOf(userId), toId);
//            mes.setConversationId(conversationId);
//            mes.setStatus(0);
//            mes.setCreateTime(LocalDateTime.now());
//            messageMapper.insert(mes);
//        });
//    }

    /**
     * 通过userId向客户端发送消息
     */
    public void sendMessageByUserId(String userId, String message) throws IOException {
        log.info("服务端发送消息到{},消息：{}",userId,message);
        if(Strings.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户{}不在线",userId);
        }
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

}
